 #include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<list>
#include<cstdlib>
#include<cmath>
#include<sstream>
#include<numeric>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;
typedef long long LL;
const int maxn=100005;
int l[maxn],r[maxn],d[maxn],p[maxn],f[17][maxn],t,n,m;
vector<int>v[maxn],e[maxn];
void dfs(int x,int y){
	d[x]=y;e[y].push_back(t);
	l[x]=t++;
	for(int i=1;(1<<i)<=n;i++)f[i][x]=f[i-1][f[i-1][x]];
	for(int i=0;i<v[x].size();i++)dfs(v[x][i],y+1);
	r[x]=t;
	}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&f[0][i]),v[f[0][i]].push_back(i);
	dfs(0,0);

	scanf("%d",&m);
	while(m--){
		int x,k;
		scanf("%d%d",&x,&k);
		vector<int> &u=e[d[x]];
		for(int i=0;(1<<i)<=n;i++)if((1<<i)&k)x=f[i][x];
		if(!x){puts("0");continue;}
		printf("%d\n",lower_bound(u.begin(),u.end(),r[x])-lower_bound(u.begin(),u.end(),l[x])-1);
		}	
    return 0;
    }
